package com.bw.gmall.realtime.dim.app;

import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TableProcessDim;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.FlinkSourceUtil;
import com.bw.gmall.realtime.common.util.HbaseUtil;
import com.bw.gmall.realtime.dim.function.DimProcessFunction;
import com.bw.gmall.realtime.dim.function.DimSinkFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @projectName: gmalll2206
 * @package: com.bw.gmall.realtime.dim.app
 * @className: DimApp2
 * @author: DuanYu
 * @description: TODO
 * @date: 2025/2/24 10:02
 * @version: 1.0
 */

public class DimApp2 extends BaseApp {
    public static void main(String[] args) {
        new DimApp2().start(Constant.TOPIC_DB, Constant.DIM_APP, 4, 10001);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {

        SingleOutputStreamOperator<JSONObject> getEtlStream = getGetEtlStream(dataStreamSource);
        getEtlStream.print();

        //        DataStreamSource<String> processStream = env.fromSource(FlinkSourceUtil.getMysqlSource(Constant.PROCESS_DATABASE, Constant.PROCESS_DIM_TABLE_NAME), WatermarkStrategy.noWatermarks(), "cdc_strteam");
//        processStream.print();
//        SingleOutputStreamOperator<TableProcessDim> createTableStream = createTable(processStream);
//        MapStateDescriptor<String,TableProcessDim> mapDescriptor = new MapStateDescriptor<String,TableProcessDim>("broadcast_state",String.class,TableProcessDim.class);
//        BroadcastStream<TableProcessDim> broadcastStream = createTableStream.broadcast(mapDescriptor);
//
//        // 3、用主流和广播流进行connect操作
//        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connectStream = getEtlStream.connect(broadcastStream).process(new DimProcessFunction(mapDescriptor));
//        // 4、过滤字段（不是所有字段都写到Hbase里面）
//        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> filterStream = getFilterStream(connectStream);
//        // 5、写入Hbase
//        filterStream.addSink(new DimSinkFunction());
    }

    private SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> getFilterStream(SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> processBroadCastStream) {
        return processBroadCastStream.map(new MapFunction<Tuple2<JSONObject, TableProcessDim>, Tuple2<JSONObject, TableProcessDim>>() {
            @Override
            public Tuple2<JSONObject, TableProcessDim> map(Tuple2<JSONObject, TableProcessDim> processDimTuple2) throws Exception {
                // 主流维度数据
                JSONObject f0 = processDimTuple2.f0;
                // 主流维度对于配置表
                TableProcessDim f1 = processDimTuple2.f1;
                // 要写入的列
                List<String> columns = Arrays.asList(f1.getSinkColumns().split(","));
                // 取出主流data
                JSONObject data = f0.getJSONObject("data");
                data.keySet().removeIf(key -> !columns.contains(key));
                return processDimTuple2;
            }
        });
    }

    private static SingleOutputStreamOperator<TableProcessDim> createTable(DataStreamSource<String> processStream) {
      return processStream.flatMap(new RichFlatMapFunction<String, TableProcessDim>() {
            private Connection hbaseConnect;
            private TableProcessDim tableProcessDim;

            @Override
            public void open(Configuration parameters) throws Exception {
                hbaseConnect = HbaseUtil.getHbaseConnect();
            }

            @Override
            public void close() throws Exception {
                hbaseConnect.close();
            }

            @Override
            public void flatMap(String s, Collector<TableProcessDim> collector) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(s);
                String op = jsonObject.getString("op");
                if ("c".equals(op) || "r".equals(op)) {
                    tableProcessDim = jsonObject.getObject("after", TableProcessDim.class);
                    String[] split = tableProcessDim.getSinkFamily().split(",");
                    createTable(split);
                } else if ("d".equals(op)) {
                    tableProcessDim = jsonObject.getObject("before", TableProcessDim.class);
                    deleteTable();
                } else if ("u".equals(op)) {
                    tableProcessDim = jsonObject.getObject("after", TableProcessDim.class);
                    String[] split = tableProcessDim.getSinkTable().split(",");
                    deleteTable();
                    createTable(split);
                }
                tableProcessDim.setOp(op);
                collector.collect(tableProcessDim);
            }

            public void createTable(String[] families) {
                try {
                    HbaseUtil.createHBaseTable(hbaseConnect, Constant.HBASE_NAMESPACE, tableProcessDim.getSinkTable(), families);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            public void deleteTable() {
                try {
                    HbaseUtil.dropHBaseTable(hbaseConnect, Constant.HBASE_NAMESPACE, tableProcessDim.getSinkTable());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).setParallelism(1);
    }

    private static SingleOutputStreamOperator<JSONObject> getGetEtlStream(DataStreamSource<String> dataStreamSource) {
        return dataStreamSource.flatMap(new RichFlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    if (s != null) {
                        JSONObject jsonObject = JSONObject.parseObject(s);
                        String database = jsonObject.getString("database");
                        String type = jsonObject.getString("type");
                        String data = jsonObject.getString("data");
                        if (!"gmall".equals(database) && !"bootstrap-start".equals(type) && !"boostrap-complete".equals(type) && data != null && data.length() > 0) {
                            collector.collect(jsonObject);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
